package com.virtualperson.controller;

import com.virtualperson.dto.TtsRequestDTO;
import com.virtualperson.dto.TtsResponseDTO;
import com.virtualperson.service.TtsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Controller
@RequestMapping("/api/tts")
@RequiredArgsConstructor
@Tag(name = "语音合成服务", description = "提供文本转语音的REST API接口")
public class TtsController {

    private final TtsService ttsService;

    @Operation(
        summary = "TTS页面",
        description = "返回语音合成的前端页面"
    )
    @GetMapping("/page")
    public String ttsPage() {
        return "tts";
    }

    @Operation(
        summary = "语音合成",
        description = "将文本转换为语音，支持流式合成和同步合成两种模式"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200",
            description = "合成成功",
            content = @Content(mediaType = "audio/*")
        ),
        @ApiResponse(
            responseCode = "400",
            description = "请求参数错误",
            content = @Content(mediaType = "application/json",
                schema = @Schema(implementation = ErrorResponse.class))
        ),
        @ApiResponse(
            responseCode = "500",
            description = "服务器内部错误",
            content = @Content(mediaType = "application/json",
                schema = @Schema(implementation = ErrorResponse.class))
        )
    })
    @PostMapping("/synthesize")
    @ResponseBody
    public ResponseEntity<?> synthesize(
        @Parameter(description = "语音合成请求参数", required = true)
        @RequestBody TtsRequestDTO request
    ) {
        log.info("收到语音合成请求: {}", request);
        
        try {
            TtsResponseDTO response = ttsService.synthesize(request);
            
            if ("SUCCESS".equals(response.getStatus())) {
                // 生成文件名
                String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
                String filename = String.format("%s_%s_%d.%s",
                    request.getModel(),
                    timestamp,
                    response.getAudioData().length,
                    request.getFormat().name().toLowerCase());

                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType(getMediaType(request.getFormat())));
                headers.setContentDispositionFormData("attachment", filename);
                headers.setContentLength(response.getAudioData().length);

                // 返回音频数据
                return ResponseEntity.ok()
                    .headers(headers)
                    .body(response.getAudioData());
            } else {
                // 返回错误信息
                return ResponseEntity.badRequest()
                    .body(new ErrorResponse(response.getStatus(), response.getMessage()));
            }
        } catch (Exception e) {
            log.error("语音合成失败", e);
            return ResponseEntity.internalServerError()
                .body(new ErrorResponse("ERROR", "语音合成服务异常: " + e.getMessage()));
        }
    }

    @Operation(
        summary = "查询合成任务状态",
        description = "根据任务ID查询语音合成任务的状态"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200",
            description = "查询成功",
            content = @Content(mediaType = "application/json",
                schema = @Schema(implementation = StatusResponse.class))
        ),
        @ApiResponse(
            responseCode = "404",
            description = "任务不存在",
            content = @Content(mediaType = "application/json",
                schema = @Schema(implementation = ErrorResponse.class))
        )
    })
    @GetMapping("/status/{taskId}")
    @ResponseBody
    public ResponseEntity<?> getStatus(
        @Parameter(description = "任务ID", required = true)
        @PathVariable String taskId
    ) {
        log.info("查询语音合成任务状态: {}", taskId);
        // TODO: 实现任务状态查询逻辑
        return ResponseEntity.ok().body(new StatusResponse("PROCESSING", "任务正在处理中"));
    }

    /**
     * 根据音频格式获取对应的MediaType
     */
    private String getMediaType(com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat format) {
        switch (format) {
            case MP3:
                return "audio/mpeg";
            case WAV:
                return "audio/wav";
            case PCM:
                return "audio/l16";
            default:
                return "application/octet-stream";
        }
    }

    /**
     * 错误响应对象
     */
    @Data
    @AllArgsConstructor
    @Schema(description = "错误响应")
    private static class ErrorResponse {
        @Schema(description = "错误状态码", example = "ERROR")
        private String status;
        
        @Schema(description = "错误信息", example = "语音合成失败")
        private String message;
    }

    /**
     * 状态响应对象
     */
    @Data
    @AllArgsConstructor
    @Schema(description = "任务状态响应")
    private static class StatusResponse {
        @Schema(description = "任务状态", example = "PROCESSING")
        private String status;
        
        @Schema(description = "状态描述", example = "任务正在处理中")
        private String message;
    }
} 